//
//  PublicLanguageVController.m
//  Experss
//
//  Created by 嗯，大葱 on 17/8/10.
//  Copyright © 2017年 嗯，大葱. All rights reserved.
//

#import "PublicLanguageVController.h"
#import "HYBStarEvaluationView.h"
//选择照片
#import "QTRejectViewCell.h"
#import "TZImagePickerController.h"
#import "XWDragCellCollectionView.h"

#import "CommentListCell.h"

//选择相册第三方
#import "JKImagePickerController.h"
#import <AssetsLibrary/AssetsLibrary.h>

@interface PublicLanguageVController ()<UITextFieldDelegate,UIScrollViewDelegate,UITextViewDelegate,UITableViewDelegate,JKImagePickerControllerDelegate,UITableViewDataSource,DidChangedStarDelegate,AFShopCartEvaluationSecondCellDelegate>
{
    XWDragCellCollectionView *_collectionView;
    UINib *_cellNib;
    
    NSString *numStarShop;//店铺的星星数
    NSMutableArray *numStartArry;//存放星级的数组
    NSMutableArray *pingjiaArray;//存放评价的数组
    
    NSMutableArray *imagePinageArray;//存放评价图片的数组
    
    
    NSInteger selectImageSecon;//记录选择照片是哪个产品
    
    NSString *numStrTep;
    int submitJ;
    int submitI;
}

@property (nonatomic, strong)NSMutableArray *imageArray;
@property (nonatomic, strong)NSString *allstr;

@property (nonatomic, strong) NSMutableArray *imagviewArr;//图片数组

@property (nonatomic, strong) NSMutableArray *assetArrarr;//选择相册第三方数组对象
@end

@implementation PublicLanguageVController

- (void)viewDidLoad {
    [super viewDidLoad];
    _imageArray = [NSMutableArray array];
    numStartArry = [NSMutableArray array];
    pingjiaArray = [NSMutableArray array];
    _imagviewArr = [NSMutableArray array];
    _assetArrarr = [NSMutableArray array];
    self.allstr = @"";
    numStarShop = @"3";
    submitI = 0;
    submitJ = 0;
    NSArray *array =_modle.order_data[@"sku_list"];
    for (int i = 0; i < array.count; i++) {
        [numStartArry addObject:@"3"];
        [pingjiaArray addObject:@""];
        [_imagviewArr addObject:[NSMutableArray array]];
        [_assetArrarr addObject:[NSMutableArray array]];
    }
    
    
    [self configureNaBar];
    [self configureView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addIMageArrayNew:) name:@"addIMageArrayNew" object:nil];
    
}
// 参数类型是NSNotification

- (void)addIMageArrayNew:(NSNotification *)notification{
    // 如果是传多个数据，那么需要哪个数据，就对应取出对应的数据即可
    [self.imageArray addObject: notification.userInfo[@"imageAray"]];
    [self.tableView reloadData];
    
}


- (void)configureNaBar {
    self.navigationItem.title = @"发表评价";
    //设置导航栏按钮的边距
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame= CGRectMake(0, 0, 60, 30);
    [rightBtn setImage:[UIImage imageNamed:@"all_fanhui2"] forState:(UIControlStateNormal)];
    [rightBtn addTarget:self action:@selector(handleBackAxtion) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *btn_left = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    UIBarButtonItem *negativeSpacerleft = [[UIBarButtonItem alloc]   initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace   target:nil action:nil];
    /**
     width为负数时，相当于btn向右移动width数值个像素，由于按钮本身和  边界间距为5pix，所以width设为-5时，间距正好调整为0；width为正数 时，正好相反，相当于往左移动width数值个像素
     */
    negativeSpacerleft.width = -20;
    self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:negativeSpacerleft, btn_left, nil];
    
    
    
    HYBStarEvaluationView *starViewUnClick = [[HYBStarEvaluationView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(_lbtitle.frame)+5, 15, 150, 20) numberOfStars:5 isVariable:YES];
    starViewUnClick.actualScore =3;
    starViewUnClick.fullScore = 5;
    starViewUnClick.isContrainsHalfStar = NO;
    starViewUnClick.tag = 2222;
    [self.bgVOnew addSubview:starViewUnClick];
    
    
    
}
- (void)handleBackAxtion {
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)configureView{
    
    
    
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.separatorStyle = kSpNone;
    _cellNib = [UINib nibWithNibName:@"CommentListCell" bundle:nil];
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    NSArray *array =_modle.order_data[@"sku_list"];
    return array.count;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0;
        
    }else {
        return 10;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, 10)];
    v.backgroundColor = KShouYeBg;
    return v;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 310;
}

- (void)imagePickerControllerDidCancel:(JKImagePickerController *)imagePicker{
    [imagePicker dismissViewControllerAnimated:YES completion:nil];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = _modle.order_data[@"sku_list"][indexPath.section];
    CommentListCell *  cell = [_cellNib instantiateWithOwner:nil options:nil][0];
    cell.selectionStyle = kSeNone;
    [cell.logoV sd_setImageWithURL:[NSURL URLWithString:dic[@"sku_image"]]];
    
    
    //留言评价
    cell.textTX.delegate =self;
    cell.textTX.tag = 101+indexPath.section;
    cell.textTX.text = pingjiaArray[indexPath.section];
    if (cell.textTX.text.length !=0) {
        cell.placeLB.hidden = YES;
    }else {
        cell.placeLB.hidden = NO;
    }
    
    //星级评价
    HYBStarEvaluationView *starViewUnClick = [[HYBStarEvaluationView alloc]initWithFrame:CGRectMake(0, 5, 150, 20) numberOfStars:5 isVariable:YES];
    NSString *bn =numStartArry[indexPath.section];
    starViewUnClick.actualScore =[bn floatValue];
    starViewUnClick.fullScore = 5;
    starViewUnClick.isContrainsHalfStar = NO;
    starViewUnClick.delegate = self;
    starViewUnClick.tag = 1001+indexPath.section;
    [cell.bgoneView addSubview:starViewUnClick];
    
    
    cell.delegate =self;
    
    
    cell.imageArr = self.imagviewArr[indexPath.section];
    [cell.collectionView reloadData];
    
    if (((NSMutableArray *)self.imagviewArr[indexPath.section]).count > 0) {
        NSIndexPath *indexpath = [NSIndexPath indexPathForItem:((NSMutableArray *)self.imagviewArr[indexPath.section]).count inSection:0];
        [cell.collectionView scrollToItemAtIndexPath:indexpath atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
    }
    
    return cell;
}

//cell的代理方法
- (void)selectImageWithCell:(UITableViewCell *)cell {
    
    NSIndexPath *index = [self.tableView indexPathForCell:cell];
    selectImageSecon = index.section;
    JKImagePickerController *imagePickerController = [[JKImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.showsCancelButton = YES;
    imagePickerController.allowsMultipleSelection = YES;
    imagePickerController.minimumNumberOfSelection = 1;
    imagePickerController.maximumNumberOfSelection = 9;
    imagePickerController.selectedAssetArray = self.assetArrarr[selectImageSecon];
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:imagePickerController];
    [self presentViewController:navigationController animated:YES completion:NULL];
				
    
    
}
- (void)imagePickerController:(JKImagePickerController *)imagePicker didSelectAssets:(NSArray *)assets isSource:(BOOL)source
{
    self.assetArrarr[selectImageSecon] = [NSMutableArray arrayWithArray:assets];
    [self.imagviewArr[selectImageSecon] removeAllObjects];
    for (JKAssets *asset in self.assetArrarr[selectImageSecon]) {
        ALAssetsLibrary   *lib = [[ALAssetsLibrary alloc] init];
        [lib assetForURL:asset.assetPropertyURL resultBlock:^(ALAsset *asset) {
            if (asset) {
                UIImage *image = [UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage]];
                [self.imagviewArr[selectImageSecon] addObject:image];
            }
        } failureBlock:^(NSError *error) {
            
        }];
    }
    [imagePicker dismissViewControllerAnimated:YES completion:^{
        [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:selectImageSecon]] withRowAnimation:(UITableViewRowAnimationNone)];
    }];
}

//改变的星星代理事件
- (void)getNumStar:(CGFloat)numStar indepath:(NSInteger )sectionTag {
    if (sectionTag == 2222) {
        numStarShop = [NSString stringWithFormat:@"%ld",sectionTag];
    }
    else {
        NSInteger t = sectionTag -1001;
        [numStartArry replaceObjectAtIndex:t withObject:[NSString stringWithFormat:@"%.f",numStar]];
    }
}




- (void)textViewDidChange:(UITextView *)textView {
    NSInteger t = textView.tag -101;
    CommentListCell *  cell = (CommentListCell *)[[textView superview] superview];
    
    if (textView.text.length == 0) {
        cell.placeLB.hidden = NO;
    }
    else {
        cell.placeLB.hidden = YES;
    }
    [pingjiaArray replaceObjectAtIndex:t withObject:textView.text];
}







#pragma mark －＝－＝－＝－＝－＝－－＝提交评价按钮的点击事件


- (IBAction)commitCommentAction:(UIButton *)sender {
    for (NSArray *arY in _imagviewArr) {
        if (arY.count == 0) {
            [MBProgressHUD showText:@"请完善图片评价"];
            return;
        }
    }
    NSArray *array =_modle.order_data[@"sku_list"];
 
    
    __weak typeof(self) wekself = self;
    NSDictionary *dic = array[submitJ];
    NSArray *tempAImage = _imagviewArr[submitJ];
    UIImage *image  = tempAImage[submitI];  //压缩图片
    NSData *fileData = UIImageJPEGRepresentation(image, 0.0);
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    NSDictionary *dic2 = @{@"file":fileData,@"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]]};
    
    AFHTTPSessionManager *Manager = [AFHTTPSessionManager manager];
    Manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/plain",@"text/html", nil];
    
    [Manager POST:POST(FileURL) parameters:dic2 constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:fileData name:@"file" fileName:@"file.png" mimeType:@"image/png"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"ret"] intValue] != 200) {
            return ;
        }
        if (![[NSString stringWithFormat:@"%@",responseObject[@"data"][@"code"]] isEqualToString:@"0"]) {
            [MBProgressHUD showText:responseObject[@"data"][@"msg"]];
            return;
        }
        NSString *photoUrl = responseObject[@"data"][@"info"][@"url"];
        if (submitI == 0) {
            numStrTep = [NSString stringWithFormat:@"%@|%@",dic[@"id"],photoUrl];
        }else {
            numStrTep = [NSString stringWithFormat:@"%@_%@",numStrTep,photoUrl];
        }
        if (submitI == tempAImage.count - 1) {
            wekself.allstr = [wekself.allstr stringByAppendingString:numStrTep];
            if (submitJ != wekself.imagviewArr.count - 1) {
                wekself.allstr = [wekself.allstr stringByAppendingString:@","];
            }
            numStrTep = @"";
            NSLog(@" %d  allstr ＝＝＝ %@",submitJ,wekself.allstr);
            submitI = 0;
            submitJ++;
            if (submitJ < array.count) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [wekself commitCommentAction:nil];
                });
            }else {
                NSLog(@"last allstr = %@",wekself.allstr);
                submitI = 0;
                submitJ = 0;
                dispatch_async(dispatch_get_main_queue(), ^{
                    [wekself pushDataToWeb];
                });
            }
        }else {
            submitI++;
            dispatch_async(dispatch_get_main_queue(), ^{
                [wekself commitCommentAction:nil];
            });
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self.view showTextNoActivity:@"服务器异常" timeLength:1];
    }];
}

- (void)pushDataToWeb {
    
   
    NSArray *array =_modle.order_data[@"sku_list"];
    //星级评价
    NSMutableArray *tOneArray = [NSMutableArray array];
    for (int i = 0; i <array.count; i++) {
        NSDictionary *dic = array[i];
        NSString *starStr = [NSString stringWithFormat:@"%@|%@",dic[@"id"],numStartArry[i]];
        [tOneArray  addObject:starStr];
    }
    NSArray *numStarA = [NSArray arrayWithArray:tOneArray];
    NSString *strTempStr =[numStarA componentsJoinedByString:@","];//多个商铺拼接留言
    
    
    //留言评价
    NSMutableArray *tTwoArray = [NSMutableArray array];
    for (int i = 0; i <array.count; i++) {
        NSDictionary *dic = array[i];
        NSString *teStr = pingjiaArray[i];
        NSString *starStr;
        if (teStr.length == 0) {
            starStr = [NSString stringWithFormat:@"%@|%@",dic[@"id"],@"没有填写评价"];
        }else {
            starStr = [NSString stringWithFormat:@"%@|%@",dic[@"id"],pingjiaArray[i]];
        }
        
        [tTwoArray  addObject:starStr];
    }
    NSArray *numStarA22 = [NSArray arrayWithArray:tTwoArray];
    NSString *strTempStr22 =[numStarA22 componentsJoinedByString:@","];//多个商铺拼接留言
    
    
    
    
    
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    NSDictionary *parameDic = @{@"userid":saveDic[@"userid"],
                                @"order_id":_modle.order_data[@"id"],
                                @"shop_level":numStarShop,
                                @"level_src":strTempStr,
                                @"desc_src":strTempStr22,
                                @"images_src":self.allstr,
                                @"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]]};
    [HttpRequest postWithURLString:POST(Shop_OrderListSubComment) parameters:parameDic success:^(id responseObject) {
        if ([responseObject[@"ret"] intValue] != 200) {
            [[DSLHUD shareDSLHUD] showTextNoActivity:@"评价出错" timeLength:1.5];
            return ;
        }
        NSString *codeStr =  responseObject[@"data"][@"code"];
        if (![[NSString stringWithFormat:@"%@",codeStr] isEqualToString:@"0"]) {
            [MBProgressHUD showText:responseObject[@"data"][@"msg"]];
            return;
        }
        [self.navigationController popViewControllerAnimated:YES];
        
        
    } failure:^(NSError *error) {
        
    }];
    
}


@end
